// @flow
import { findArticleListByTitleEs } from '@/services/articles';
import { getClientHeight, getScrollHeight, getScrollTop, warpTag } from '@/utils';
import useRequest from '@ahooksjs/use-request';
import {
  CloseOutlined,
  EnterOutlined,
  FileOutlined,
  HomeOutlined,
  SearchOutlined,
  ToTopOutlined,
} from '@ant-design/icons';
import { history } from '@umijs/max';
import type { InputRef } from 'antd';
import { Divider, Empty, Input, message, Modal, Typography } from 'antd';
import classnames from 'classnames';
import React, { useCallback, useEffect, useRef, useState } from 'react';
import InfiniteScroll from 'react-infinite-scroll-component';
import styles from './index.less';

const { Search } = Input;
const { Paragraph } = Typography;

type Props = {};
const Index: React.FC<Props> = () => {
  const searchRef = useRef<InputRef>(null);
  const [bottomPercentage, setBottomPercentage] = useState<number>(0);
  const [articleList, setArticleList] = useState<ARTICLEAPI.ARTICLE[]>([]);
  const [show, setShow] = useState<boolean>(false); // 0表示显示叉 1和2表示显示距离顶部距离百分比(并且2表示刚进来)
  const [isHiddle, setIsHiddle] = useState<boolean>(true);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const { run: findArticleListByTitleEsRun, loading: searchLoading } = useRequest(
    findArticleListByTitleEs,
    {
      debounceInterval: 300,
      manual: true,
      onSuccess: (res) => {
        const { code, data: { records = [] } = {}, message: errorMessage } = res;
        if (code === 200) {
          setArticleList([...records]);
        } else {
          message.error(errorMessage);
        }
      },
    },
  );
  const handleScroll = () => {
    const scrollTop = getScrollTop();
    const scrollHeight = getScrollHeight();
    const clientHeight = getClientHeight();
    const vla = Math.floor((scrollTop / (scrollHeight - clientHeight)) * 100);
    setBottomPercentage(vla);
  };

  const onSearch = (val: string) => {
    if (val) {
      findArticleListByTitleEsRun({
        current: 1,
        pageSize: 10,
        articleTitle: val,
      });
    }
  };
  // 加载更多
  const loadMoreData = () => {
    const val = searchRef.current?.input?.value;
    if (searchLoading) {
      return;
    }
    if (val) {
      // 加载更多
      findArticleListByTitleEsRun({
        current: 1,
        pageSize: 10,
        articleTitle: val,
        more: true,
      });
    }
  };

  const warpTagHandler = useCallback(
    (param: string) => {
      if (articleList.length > 0 && !searchLoading) {
        return warpTag(param, searchRef?.current?.input?.value || '');
      }
      return '';
    },
    [articleList, searchLoading],
  );
  useEffect(() => {
    window.addEventListener('scroll', handleScroll, true);
    // 移除监听事件
    return window.removeEventListener('scroll', handleScroll);
  }, []);

  return (
    <div
      className={classnames(
        styles.operationBallWrapper,
        !isHiddle ? styles.operationBallWrapperSecret : null,
      )}
      onMouseOut={() => {
        if (!show) {
          setIsHiddle(true);
        }
      }}
      onMouseMove={() => setIsHiddle(false)}
    >
      <div className={styles.operationBall}>
        {show ? (
          <CloseOutlined
            onClick={() => {
              if (!isHiddle) {
                setShow(false);
              }
            }}
            className={styles.iconWrapper}
          />
        ) : (
          <div onClick={() => setShow(true)} className={styles.bottomPercentage}>
            {bottomPercentage || 0}%
          </div>
        )}
      </div>
      <div className={styles.operationWrapper}>
        <div
          onClick={() => window.scrollTo(0, 0)}
          className={classnames(styles.toolCommon, show ? styles.toolCommonRotate : null)}
          style={{ '--i': 0 }}
        >
          <ToTopOutlined />
        </div>
        <div
          onClick={() => {
            history.push('/plaza');
          }}
          className={classnames(styles.toolCommon, show ? styles.toolCommonRotate : null)}
          style={{ '--i': 1 }}
        >
          <HomeOutlined />
        </div>
        <div
          onClick={() => setIsModalOpen(true)}
          className={classnames(styles.toolCommon, show ? styles.toolCommonRotate : null)}
          style={{ '--i': 2 }}
        >
          <SearchOutlined />
        </div>
      </div>
      <Modal
        className={styles.mySearchModalWrapper}
        bodyStyle={{ backgroundColor: '#ddd' }}
        footer={false}
        open={isModalOpen}
        closable={false}
        onCancel={() => setIsModalOpen(false)}
      >
        <Search
          ref={searchRef}
          className={styles.searchInput}
          placeholder="请输入要搜索的内容"
          onChange={(e) => onSearch(e.target.value)}
          loading={searchLoading}
          onSearch={onSearch}
          enterButton
        />
        {articleList.length > 0 ? (
          <div className={styles.searchList}>
            <InfiniteScroll
              dataLength={articleList.length}
              next={loadMoreData}
              hasMore={articleList.length < 50}
              loader={<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
              endMessage={<Divider plain>没有更多了,快去创作吧!</Divider>}
              scrollableTarget="scrollableDiv"
            >
              {articleList.map((item) => {
                return (
                  <div
                    className={styles.searchListItem}
                    key={item.id}
                    onClick={() => window.open(`/article/view/${item.articleId}`)}
                  >
                    <div className={styles.leftWrapper}>
                      <FileOutlined />
                      <div className={styles.titleWrapper}>
                        <div
                          className={styles.title}
                          dangerouslySetInnerHTML={{
                            __html: warpTagHandler(item.articleTitle),
                          }}
                        />
                        <div className={styles.subTitle}>
                          <Paragraph className="contents" ellipsis={{ rows: 2 }}>
                            <div
                              className={styles.title}
                              dangerouslySetInnerHTML={{
                                __html: warpTagHandler(item.articleContent),
                              }}
                            />
                          </Paragraph>
                        </div>
                      </div>
                    </div>
                    <EnterOutlined />
                  </div>
                );
              })}
            </InfiniteScroll>
          </div>
        ) : (
          <>
            <div className={styles.recentlySearch}>最近搜索</div>
            <div className={styles.searchList}>
              {[
                {
                  articleId: 31,
                  articleTitle: 'Java excel 导入',
                  articleContent:
                    '内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容',
                  articleIsPrivate: 0,
                  articleAuthor: 1,
                  articleCreationTime: '2023-03-15T12:32:11.000+00:00',
                  articleAmendTime: '2023-05-13T11:53:51.000+00:00',
                  articleCreationLocation: '0',
                  articleCustomizedIsAutosave: 0,
                  user: {
                    id: 1,
                    nickname: '哈哈',
                    headPortrait:
                      'http://119.23.173.237/image/CreateFreely/headPortrait/%E5%8F%B2%E8%BF%AA%E4%BB%94.jpg',
                  },
                  articleInteraction: {
                    articleInteractionId: 33,
                    articleInteractionArticleId: 31,
                    articleLikeCount: 0,
                    articleLookCount: 1,
                    articleCommentCount: 0,
                    articleCollectCount: 0,
                  },
                },
                {
                  articleId: 32,
                  articleTitle: 'Java springboot 导入',
                  articleContent:
                    '内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容',
                  articleIsPrivate: 0,
                  articleAuthor: 1,
                  articleCreationTime: '2023-03-15T12:35:46.000+00:00',
                  articleAmendTime: '2023-05-13T11:54:01.000+00:00',
                  articleCreationLocation: '0',
                  articleCustomizedIsAutosave: 0,
                  user: {
                    id: 1,
                    nickname: '哈哈',
                    headPortrait:
                      'http://119.23.173.237/image/CreateFreely/headPortrait/%E5%8F%B2%E8%BF%AA%E4%BB%94.jpg',
                  },
                  articleInteraction: {
                    articleInteractionId: 34,
                    articleInteractionArticleId: 32,
                    articleLikeCount: 0,
                    articleLookCount: 1,
                    articleCommentCount: 0,
                    articleCollectCount: 0,
                  },
                },
              ].map((item) => {
                return (
                  <div
                    className={styles.searchListItem}
                    key={item.articleId}
                    onClick={() => window.open(`/article/view/${item.articleId}`)}
                  >
                    <div className={styles.leftWrapper}>
                      <FileOutlined />
                      <div className={styles.titleWrapper}>
                        <div className={styles.title}>{item.articleTitle}</div>
                        <div className={styles.subTitle}>
                          <Paragraph className="contents" ellipsis={{ rows: 2 }}>
                            {item.articleContent}
                          </Paragraph>
                        </div>
                      </div>
                    </div>
                    <EnterOutlined />
                  </div>
                );
              })}
            </div>
          </>
        )}
      </Modal>
    </div>
  );
};
export default Index;
